/**
* @auther kinglbx
* @date 2025-05-10 18:03
*/
// 检查 jQuery 对象是否存在
if (typeof jQuery !== 'undefined') {
    console.log('jQuery 已加载，版本：' + jQuery.fn.jquery);
} else {
    console.log('jQuery 未加载');
}

let quickLoginPanelHtml =
    `<div id="Kinglbx_quickLogin_panel"
    style="
        position: absolute;
        top: 1px;
        left: 1px;
        z-index: 10000;
        width: 300px;
        height: 500px;
        background:none;
        border: 1px solid #cccccc;
        border-radius: 10px;
        padding: 10px;
    ">
    <div style="display: inline-block; text-align: center; width: 300px; height: 30px; font-weight: bold; font-size: 18px;">快捷登录面板</div>
    <div style="width: 300px; height: 300px;">
    <span>用户列表</span>
    <button id="Kinglbx_quickLogin_setting"
            style="
            width: 80px;
            padding: 2px;
            background-color: #165DFF;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            transition: background-color 0.3s;" >打开设置</button>
    <button id="Kinglbx_quickLogin_account"
            style="
            width: 80px;
            padding: 2px;
            background-color: #165DFF;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
            transition: background-color 0.3s;">新增账号</button>
    <br/>
    <table style="border-collapse: collapse; border: 1px solid #ddd; margin-top:10px;">
        <thead>
            <tr>
                <th style="text-align: left; border: 1px solid #ddd; padding:3px;">序号&emsp;&emsp;</th>
                <th style="text-align: left; border: 1px solid #ddd; padding:3px;">登录名&emsp;&emsp;</th>
            </tr>
        </thead>
        <tbody id="Kinglbx_quickLogin_account_table">
            
        </tbody>
    </table>
    </div>
</div>
<div id="Kinglbx_quickLogin_setting_panel"
    style="position: absolute;
    top: 300px;
    left: 500px;
    z-index: 10100;
    width: 350px;
    height: 210px;
    background-color: #ffffff;
    border-radius: 10px;
    border: 1px solid #cccccc;
    display: none;
    padding: 10px;
    ">
    <div style="width: 100%; text-align: center; font-weight: bold; font-size: 16px;">设置</div>
    默认显示<input type="checkbox" /><br/>
    绑定登录名元素&emsp;<input type="text" placeholder="请输入元素id或其任意class" /><br/>
    绑定密码元素&emsp;&emsp;<input type="text" placeholder="请输入元素id或其任意class" /><br/>
    绑定登录按钮元素<input type="text" placeholder="请输入元素id或其任意class" /><br/>
    <div style="width: 100%; text-align: center; font-weight: bold; font-size: 16px; padding:10px;">
        <button id="Kinglbx_quickLogin_setting_close">关闭</button>
        <button id="Kinglbx_quickLogin_setting_save">保存</button>
    </div>
</div>
<div id="Kinglbx_quickLogin_account_panel"
    style="position: absolute;
    top: 300px;
    left: 500px;
    z-index: 10100;
    width: 350px;
    height: 210px;
    background-color: #ffffff;
    border-radius: 10px;
    border: 1px solid #cccccc;
    display: none;
    padding: 10px;
    ">
    <div style="width: 100%; text-align: center; font-weight: bold; font-size: 16px;">新增账号</div>
    登录名<input type="text" placeholder="请输入登录名" /><br/>
    密&emsp;码<input type="text" placeholder="请输入密码" /><br/>
    <div style="width: 100%; text-align: center; font-weight: bold; font-size: 16px; padding: 10px;">
        <button id="Kinglbx_quickLogin_account_close">关闭</button>
        <button id="Kinglbx_quickLogin_account_save">保存</button>
    </div>
</div>
`;

let quickLoginObj = {

    quickLoginDataKey: "quickLoginData", 
    quickLoginDataDefault:
    {   
        accountList: [],
        settingData:{
            isShow: false,
            userNameEvemt: "username",
            passwordEvemt: "password",
            submitButtonEvemt: "button1",
            mainPanelPositionTop: "1px",
            mainPanelPositionLeft: "1px"
        }
    },
    
    run: () => {
        //
        quickLoginObj.checkQuickLoginData();
        quickLoginObj.initKeyboardListener();
        quickLoginObj.eventListener();
    },
    checkQuickLoginData: () => {
        let quickLoginData = quickLoginObj.getQuickLoginData();
        if(quickLoginData === ""){
            quickLoginObj.setQuickLoginData(quickLoginObj.quickLoginDataDefault);
        }else{
            // 是否主动显示快捷登录面板
            let quickLoginData = quickLoginObj.getQuickLoginData();
            let settingData = quickLoginData.settingData;
            if(settingData.isShow){
                quickLoginObj.renderMainPanel();
            }
        }
    },
    renderMainPanel: ()=>{
        $('body').append(quickLoginPanelHtml);
        quickLoginObj.draggable();
        quickLoginObj.refreshAccountList();
        // 渲染位置
        let quickLoginData = quickLoginObj.getQuickLoginData();
        let settingData = quickLoginData.settingData;
        $("#Kinglbx_quickLogin_panel").css("top", settingData.mainPanelPositionTop === "NaNpx"?"1px" : settingData.mainPanelPositionTop );
        $("#Kinglbx_quickLogin_panel").css("left", settingData.mainPanelPositionLeft === "NaNpx"?"1px" : settingData.mainPanelPositionLeft );
    },
    initKeyboardListener: () => {
        $(document).keydown(function (e) {
            // 检测Ctrl+L组合键
            if (e.altKey && e.key === 'l') {
                if ($("#Kinglbx_quickLogin_panel").length === 0) {
                    quickLoginObj.renderMainPanel();
                }
            }
        });
    },
    eventListener: () => {
        // 显示设置弹框
        $(document).off("click", "#Kinglbx_quickLogin_setting").on("click", "#Kinglbx_quickLogin_setting", () => {
            $("#Kinglbx_quickLogin_setting_panel").css("display", "inline");
            $("#Kinglbx_quickLogin_account_panel").css("display", "none");
            let quickLoginData = quickLoginObj.getQuickLoginData();
             let settingData = quickLoginData.settingData;
            
            // 界面取值
             let settingInputs = $("#Kinglbx_quickLogin_setting_panel").find("input");
             
            // 是否默认显示
            settingInputs.eq(0).prop("checked", settingData.isShow);
            settingInputs.eq(1).val(settingData.userNameEvemt);
            settingInputs.eq(2).val(settingData.passwordEvemt);
            settingInputs.eq(3).val(settingData.submitButtonEvemt);
        });
        // 显示账号弹框
        $(document).off("click", "#Kinglbx_quickLogin_account").on("click", "#Kinglbx_quickLogin_account", () => {
            $("#Kinglbx_quickLogin_setting_panel").css("display", "none");
            $("#Kinglbx_quickLogin_account_panel").css("display", "inline");
$("#Kinglbx_quickLogin_account_panel").find("input").eq(0).val("");
$("#Kinglbx_quickLogin_account_panel").find("input").eq(1).val("");
        });
        // 关闭设置弹框
        $(document).off("click", "#Kinglbx_quickLogin_setting_close").on("click", "#Kinglbx_quickLogin_setting_close", () => {
            quickLoginObj.closeAllDlg();
        });
         // 关闭账号弹框
        $(document).off("click", "#Kinglbx_quickLogin_account_close").on("click", "#Kinglbx_quickLogin_account_close", () => {
            quickLoginObj.closeAllDlg();
        });
        // 保存设置
        $(document).off("click", "#Kinglbx_quickLogin_setting_save").on("click", "#Kinglbx_quickLogin_setting_save", () => {
             let quickLoginData = quickLoginObj.getQuickLoginData();
             let settingData = quickLoginData.settingData;
            
            // 界面取值
             let settingInputs = $("#Kinglbx_quickLogin_setting_panel").find("input");
             
            // 是否默认显示
            settingData.isShow = settingInputs.eq(0).is(":checked");
            settingData.userNameEvemt = settingInputs.eq(1).val();
            settingData.passwordEvemt = settingInputs.eq(2).val();
            settingData.submitButtonEvemt = settingInputs.eq(3).val();
            quickLoginObj.setQuickLoginData(quickLoginData);
            quickLoginObj.closeAllDlg();
        });

        // 保存账号
        $(document).off("click", "#Kinglbx_quickLogin_account_save").on("click", "#Kinglbx_quickLogin_account_save", () => {
            // 界面取值
            let userName = $("#Kinglbx_quickLogin_account_panel").find("input").eq(0).val();
            let password = $("#Kinglbx_quickLogin_account_panel").find("input").eq(1).val();

           let quickLoginData = quickLoginObj.getQuickLoginData();
           let accountList = quickLoginData.accountList;
           // 
           for(let i=0; i<accountList.length; i++){
                let e = accountList[i];
                if(userName === e.userName){
                    e.password = password;
                    quickLoginObj.setQuickLoginData(quickLoginData);
                    return;
                }
           }
            accountList.push({
                userName: userName,
                password: password
            });
            quickLoginObj.setQuickLoginData(quickLoginData);
            quickLoginObj.closeAllDlg();
            quickLoginObj.refreshAccountList();
        });

        // 点击-登录名称登录
        $(document).off("click", ".Kinglbx_quickLogin_goLogin").on("click", ".Kinglbx_quickLogin_goLogin", (e) => {
            // 获取本地数据
            let quickLoginData = quickLoginObj.getQuickLoginData();
            let accountIndex = $(e.target).attr("index");

            let accountList = quickLoginData.accountList;
            let settingData = quickLoginData.settingData;

            let selectAccount = accountList[accountIndex];

            let userNameEvemt = $(`#${settingData.userNameEvemt}`);
            if (userNameEvemt.length === 0) {
                userNameEvemt = $(`.${settingData.userNameEvemt}`);
                 if (userNameEvemt.length === 0) {
                    userNameEvemt = $(`input[name="${settingData.userNameEvemt}"]`);
                 }
            }
           

            let passwordEvemt = $(`#${settingData.passwordEvemt}`);
            if (passwordEvemt.length === 0) {
                passwordEvemt = $(`.${settingData.passwordEvemt}`);
                 if (passwordEvemt.length === 0) {
                    passwordEvemt = $(`input[name="${settingData.passwordEvemt}"]`);
                 }
            }
            

            let submitButtonEvemt = $(`#${settingData.submitButtonEvemt}`);
            if (submitButtonEvemt.length === 0) {
                submitButtonEvemt = $(`.${settingData.submitButtonEvemt}`);
            }

            // 赋值
            userNameEvemt.val(selectAccount.userName);
            passwordEvemt.val(selectAccount.password);

            // 登录
            submitButtonEvemt.click();
        });

    },
    closeAllDlg: ()=>{
        $("#Kinglbx_quickLogin_setting_panel").css("display", "none");
        $("#Kinglbx_quickLogin_account_panel").css("display", "none");
    },

    draggable: () => {
        const element = document.getElementById('Kinglbx_quickLogin_panel');
        let isDragging = false;
        let offsetX, offsetY;

        // 鼠标按下事件
        element.addEventListener('mousedown', function (e) {
            isDragging = true;
            offsetX = e.clientX - element.getBoundingClientRect().left;
            offsetY = e.clientY - element.getBoundingClientRect().top;
            element.classList.add('dragging');
            // 防止拖拽过程中选择文本
            e.preventDefault();
        });

        // 鼠标移动事件
        document.addEventListener('mousemove', function (e) {
            if (!isDragging) return;

            const x = e.clientX - offsetX;
            const y = e.clientY - offsetY;

            // 设置元素位置
            element.style.left = x + 'px';
            element.style.top = y + 'px';
        });

        // 鼠标释放事件
        document.addEventListener('mouseup', function (e) {
            isDragging = false;
            element.classList.remove('dragging');
            const x = e.clientX - offsetX;
            const y = e.clientY - offsetY;
            // 设置位置
            let quickLoginData = quickLoginObj.getQuickLoginData();
            let settingData = quickLoginData.settingData;
            
            settingData.mainPanelPositionTop = y+ "px",
            settingData.mainPanelPositionLeft = x + "px"
            quickLoginObj.setQuickLoginData(quickLoginData);
        });
    },

    getQuickLoginData: () => {
        try {
            let key = quickLoginObj.quickLoginDataKey;
            const jsonValue = localStorage.getItem(key);
            // 如果值不存在，返回默认值
            if (jsonValue === null) {
                return "";
            }
            // 解析JSON字符串
            return JSON.parse(jsonValue);
        } catch (error) {
            console.error(`从localStorage读取失败: ${error.message}`);
            return "";
        }
    },

    setQuickLoginData: (data) => {
        try {
            let key = quickLoginObj.quickLoginDataKey;
            // 将数据转换为JSON字符串
            const jsonValue = JSON.stringify(data);
            localStorage.setItem(key, jsonValue);
            console.log(`数据已保存到localStorage，键: ${key}`);
        } catch (error) {
            console.error(`保存到localStorage失败: ${error.message}`);
        }
    },

    refreshAccountList: () => {
        let accountListHtml = "";
        let quickLoginData = quickLoginObj.getQuickLoginData();
        let accountList = quickLoginData.accountList;
        for(let i=0; i<accountList.length; i++){
            let e = accountList[i];
            accountListHtml += `<tr>
                <td style="text-align: left; border: 1px solid #ddd; padding:3px;">${i+1}</td>
                <td class="Kinglbx_quickLogin_goLogin" 
                    style="text-align: left; border: 1px solid #ddd; cursor: pointer;  padding:3px; color: #165DFF;" 
                    index="${i}">
                    ${e.userName}
                </td>
            </tr>`;
        }
        $("#Kinglbx_quickLogin_account_table").html(accountListHtml);
    }
}

// 执行
$(document).ready(()=>{
	quickLoginObj.run();
});
